package com.geek.gkfgw.framework.validator;

import org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator;
import org.hibernate.validator.resourceloading.AggregateResourceBundleLocator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Arrays;
import java.util.Set;

/**
 * <h1>校验工具类。</h1><br/>
 *
 * <h1><br/><a href="https://u.geekbang.org/subject/arch3/100614201">Java 业务架构实战营：https://u.geekbang.org/subject/arch3/100614201</a></h1><br/><h1><a href="https://gitee.com/ylimhhmily/BizArchPracticeCamp">Java 业务架构实战营代码地址：https://gitee.com/ylimhhmily/BizArchPracticeCamp</a></h1><br/><h1><a href="https://u.geekbang.org/subject/java4th/1001148?source=app_share">高级 Java 工程体系课 2023 版：https://u.geekbang.org/subject/java4th/1001148?source=app_share</a></h1><br/><h1><a href="https://time.geekbang.org/column/intro/100312101?tab=catalog">Dubbo 源码剖析与实战：https://time.geekbang.org/column/intro/100312101?tab=catalog</a></h1>
 *
 * @author hmilyylimh
 *         ^_^
 * @version 0.0.1
 *         ^_^
 * @date 2022-02-18
 *
 */
public class HibernateValidator {

    private static Validator validator;

    static {
        ValidatorFactory factory = (Validation.byProvider(org.hibernate.validator.HibernateValidator.class).configure())
                .failFast(true).messageInterpolator(new ResourceBundleMessageInterpolator(
                        new AggregateResourceBundleLocator(Arrays.asList("validationMessage"))))
                .buildValidatorFactory();
        validator = factory.getValidator();
    }

    public static String validate(Object obj) {
        if (null == obj) {
            return "对象不能为空";
        }

        StringBuilder message = new StringBuilder("");
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(obj);
        int size = constraintViolations.size();
        if (size == 0) {
            return "";
        }
        int idx = 0;
        for (ConstraintViolation<Object> v : constraintViolations) {
            message.append(v.getPropertyPath()).append(" ").append(v.getMessage());
            idx += 1;
            if (idx < size) {
                message.append("; ");
            }
        }
        return message.toString();
    }
}
